package jch.learn.java.advanced.chapter2_InputAndOutput;

import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class TestFilesVisit {

    public static void main(String[] args) throws IOException {
        Path resources = Paths.get(TestFilesVisit.class.getResource("/").getPath().substring(1));

        // 获取目录中的项 注意：Files.list(Path path) 处理的目录是被惰性读取的。
        System.out.println("Files.list 访问目录中的项：");
        try (Stream<Path> entries = Files.list(resources)) {
            entries.forEach(System.out::println);
        }
        System.out.println("------");

        // 获取目录中的项 及其下属子目录
        System.out.println("Files.walk 访问目录中的项(包含子目录): ");
        // 添加跟踪符号链接
        try (Stream<Path> e = Files.walk(resources, FileVisitOption.FOLLOW_LINKS)) {
            e.forEach(System.out::println);
        }

        //
        System.out.println("---------");
        try(Stream<Path> e = Files.walk(resources)){
            e.forEach(System.out::println);
        }

//        copyDF();
    }

    private static void copyDF() throws IOException {
        Path target = Paths.get(TestFilesVisit.class.getResource("/").getPath().substring(1));
        Path path =Paths.get(TestFilesVisit.class.getResource("/chapter2/copy").getPath().substring(1));
        Files.walk(path).forEach(p -> {
            try {
                Path q = target.resolve(path.relativize(p));
                if (Files.isDirectory(p)){
                    Files.createDirectory(q);
                } else {
                    Files.copy(p,q);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
